//
//  EventCenterVC.m
//  ConvenientlyTake
//
//  Created by 张奇 on 2022/12/20.
//

#import "EventCenterVC.h"
#import "EventCenterCell.h"
#import "EventCenterAPIRequest.h"
#import "EventCenterModel.h"
#import "EventDetailVC.h"
#import "AppDelegate+JPush.h"
#import "UITabBarItem+PPBadgeView.h"
#import "EventDetailAPIRequest.h"

@interface EventCenterVC ()<QMUITableViewDelegate, QMUITableViewDataSource, UISearchBarDelegate>

@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) QMUIButton *filterBtn;
@property (nonatomic, strong) QMUITableView *tableView;

@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) NSInteger eventState;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSString *promoter; // 搜索条件
@property (nonatomic, strong) NSArray *filterArray;

@end

@implementation EventCenterVC

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self requestUnReadCount];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    self.eventState = -1;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requesData) name:KNotificationWithRefresheEventCenterVC object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestUnReadCount) name:KNotificationWithRefresheEventCount object:nil];
    [self requestEventState];
}

- (void)setupNavigationItems {
    [super setupNavigationItems];
    [self setNavStyleWhite];
}

-(void)requesData{
    [self requestDataIsFirstPage:YES];
}
-(void)requestEventState{
    [EventDetailAPIRequest GETEventStateSuccess:^(TGResponseItem *responseItem) {
        if (responseItem.success) {
            /**处理数据**/
            NSArray *array = responseItem.data;
            NSMutableArray *resultArr = [NSMutableArray arrayWithCapacity:array.count];
            for (NSDictionary *item in array) {
                [resultArr addObject:item[@"name"]];
            }
            [resultArr insertObject:@"全部" atIndex:0];
            self.filterArray = resultArr;
        }
    } fail:^(NSError *error) {
        
    }];
    [self requesData];
}

- (void)requestDataIsFirstPage:(BOOL)isFirstPage {
    if(isFirstPage){
        self.page = 1;
    }
    [TGProgressHUD showHUD:nil];
    [EventCenterAPIRequest GETEventWithEventState:self.eventState page:self.page promoter:self.promoter success:^(TGResponseItem *responseItem) {
        [TGProgressHUD dismissMPHUD];
        if (responseItem.success) {
            self.page++;
            if (isFirstPage) {
                [self.dataArray removeAllObjects];
            }
            NSArray *list = [NSArray modelArrayWithClass:[EventCenterModel class] json:responseItem.data];
            [self.dataArray addObjectsFromArray:list];
            [self.tableView isShowFooter:list];
        }
        [self endRequestLoad];
    } fail:^(NSError *error) {
        [self endRequestLoad];
    }];
}

- (void)endRequestLoad {

    [self.tableView reloadData];
    [self.tableView endPullUp];
    [self.tableView endPullDown];
}


- (void)setupUI {
    
    UIView *topView = [[UIView alloc] init];
    topView.backgroundColor = UIColorWhite;
    [self.view addSubview:topView];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(0);
        make.height.mas_equalTo(RatioWidth(60));
    }];
    
    [topView addSubview:self.searchBar];
    [_searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(RatioWidth(12));
        make.left.mas_equalTo(RatioWidth(5));
        make.height.mas_equalTo(RatioWidth(38));
    }];
    
    [topView addSubview:self.filterBtn];
    [_filterBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.searchBar);
        make.left.equalTo(self.searchBar.mas_right);
        make.right.mas_equalTo(-RatioWidth(12));
        make.size.mas_equalTo(CGSizeMake(RatioWidth(25), RatioWidth(25)));
    }];
    
    [self.view addSubview:self.tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(RatioWidth(60));
        make.left.right.mas_offset(0);
        make.bottom.mas_offset(0);
    }];
    _tableView.ly_emptyView = [MyEmptyView emptyWithContentViewDetailStr:@"暂时没有记录哦！" imageStr:@"empty_nodata" btnClickBlock:nil configerBlock:^(MyEmptyView *configer) {
        configer.contentViewOffset = -RatioHeight(50);
        configer.imageSize = CGSizeMake(RatioWidth(200), RatioWidth(200));
    }];

}

- (void)clickFilterAction:(QMUIButton *)sender {
    [TGLEEAlert actionSheetTitle:@"" buttons:self.filterArray isHaveCancleAction:YES canClickBackgroundClose:YES click:^(NSInteger index) {
        self.eventState = index;
        [self requestDataIsFirstPage:YES];
        
    }]; 
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    self.promoter = searchBar.text;
//    [self requestDataIsFirstPage:YES];
    [searchBar endEditing:YES];
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    self.promoter = searchBar.text;
    [self requestDataIsFirstPage:YES];
}
#pragma mark 数据源代理

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    EventCenterCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EventCenterCell"];
    cell.eventModel = self.dataArray[indexPath.row];
    return cell;
}

- (void)requestUnReadCount {
    [EventCenterAPIRequest GETCountByCurrentUserWithSuccess:^(TGResponseItem *responseItem) {
        if (responseItem.success) {
            
            NSInteger count = [responseItem.data integerValue];
            UITabBarController * root = self.tabBarController;
            UITabBarItem * tabBarItem = [UITabBarItem new];
            tabBarItem = root.tabBar.items[0];
            
            if (count > 0) {
                [tabBarItem pp_addBadgeWithNumber:count];
                [tabBarItem pp_showBadge];
//                [tabBarItem pp_setBadgeHeight:15];
                [tabBarItem pp_moveBadgeWithX:-3 Y:3];
            } else {
                [tabBarItem pp_hiddenBadge];
            }
        }
    } fail:^(NSError *error) {
        
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.view endEditing:YES];
    EventCenterModel *model = self.dataArray[indexPath.row];
    EventDetailVC *vc = [[EventDetailVC alloc] init];
    vc.eventId =  model.eventId;
    [self pushViewController:vc complent:nil];
}

- (UISearchBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc] init];
        _searchBar.placeholder = @"请输入提交人/手机号查询";
        _searchBar.qmui_placeholderColor = RGB(202, 205, 212);
        _searchBar.qmui_textField.font = TGAutoFont(14);
        _searchBar.backgroundImage = [UIImage qmui_imageWithColor:UIColorClear];
        
        _searchBar.qmui_textField.backgroundColor = RGB(242, 243, 245);
        _searchBar.qmui_textField.layer.cornerRadius = 3;
        _searchBar.qmui_textField.layer.borderColor = RGB(242, 243, 245).CGColor;
        _searchBar.qmui_textField.layer.borderWidth = 5;
        _searchBar.delegate = self;
                
    }
    return _searchBar;
}

- (QMUIButton *)filterBtn {
    if (!_filterBtn) {
        _filterBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
        [_filterBtn setImage:kImage(@"eventCenter_filter") forState:UIControlStateNormal];
        [_filterBtn addTarget:self action:@selector(clickFilterAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _filterBtn;
}

- (QMUITableView *)tableView {
    if (!_tableView) {
        _tableView = [[QMTableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = UIColorClear;
        _tableView.estimatedRowHeight = RatioWidth(200);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        [_tableView registerNib:[UINib nibWithNibName:@"EventCenterCell" bundle:nil] forCellReuseIdentifier:@"EventCenterCell"];
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        
        WEAK
        [_tableView addLegendHeaderWithRefreshingBlock:^{
            STRONG
            [self requestDataIsFirstPage:YES];
        }];
        [_tableView addLegendFooterWithRefreshingBlock:^{
            STRONG
            [self requestDataIsFirstPage:NO];
        }];
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, TableViewSpace)];
        [_tableView hideFooter];
        [_tableView startPullDown];
          
    }
    return _tableView;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
//事件状态(1-待受理; 2-指派中；3-处理中；4-局委审核中；5-宣传部审核中;6-已办结;7-不予受理)
//- (NSArray *)filterArray{
//    if (!_filterArray) {
//        _filterArray = @[@"全部",@"待受理",@"指派中" , @"处理中" , @"局委审核中" , @"宣传部审核中" ,@"已办结",@"不予受理"];
//    }
//    return _filterArray;
//}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
